#include "udpServer.hpp"
#include <memory>
#include <cstdio>
#include <vector>

// "120.78.126.148" 点分十进制字符串风格的IP地址
// 4个字节ip地址,但是用户不关心

void Usage(string proc)
{
    cout << "\n\tUsage: " << proc << " port[1024+]" << endl;
}

string Handler(const string &str , const string& ip, uint16_t& port)
{
    cout << "[" << ip << ":" << port << "]# ";
    std::string res = "Server get a message: ";
    res += str;
    std::cout << res << std::endl;
    return res;
}


bool SafeCheck(const string &cmd)
{
    vector<string> key_word = {
        "rm",
        "mv",
        "cp",
        "kill",
        "sudo",
        "unlink",
        "uninstall",
        "yum",
        "top",
        "while"};
    for (auto e : key_word)
    {
        auto pos = cmd.find(e);
        if (pos != string::npos)
        {
            return false;
        }
    }
    return true;
}

std::string ExcuteCommand(const std::string &cmd)
{
    if (!SafeCheck(cmd))// 安全检查
        return "Bad man";
    // popen创建一个管道并来启动一个子进程执行shell命令
    // 随后通过管道将执行的命令给父进程
    // 父进程可以通过打开文件来看执行结果
    FILE *fp = popen(cmd.c_str(), "r");
    if (nullptr == fp)
    {
        perror("popen");
        return "error";
    }
    std::string result;
    char buffer[4096];
    while (true)
    {
        char *ok = fgets(buffer, sizeof(buffer), fp);
        if (ok == nullptr)
            break;
        result += buffer;
    }
    pclose(fp);
    return result;
}

// ./udpserver port
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(0);
    }

    uint16_t port = stoi(argv[1]);

    unique_ptr<UdpServer> svr(new UdpServer(port));
    svr->Init();
    svr->Run();
    return 0;
}

/*
#define ADD(num, value) sum##num += value;

int main()
{
    int sum1 = 5;
    cout << sum1 << endl;
    int ret = ADD(1, 10); //将sum1加10
    cout << sum1 << endl;
    return 0;
}
*/